/*
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.orm.factory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;

import cc.aileron.accessor.PojoAccessorValueNotFoundException;
import cc.aileron.accessor.PojoPropertiesNotFoundException;
import cc.aileron.commons.instance.InstanceManager;
import cc.aileron.orm.annotation.G2Id;
import cc.aileron.orm.exception.SqlNotFoundRuntimeException;
import cc.aileron.orm.factory.serial.G2DaoSerial;
import cc.aileron.orm.sql.G2DaoSqlMap;

/**
 * @author Aileron
 * @param <T>
 * 
 */
public class G2DaoExecuteInvokerImpl<T> implements G2DaoExecuteInvoker<T>
{
    @Override
    public int execute(final Category category,
            final Connection connection,
            final T bean) throws SQLException,
            PojoAccessorValueNotFoundException,
            PojoPropertiesNotFoundException
    {
        final String name = category.name()
            .toLowerCase();
        final PreparedStatement statement = statementFactory.create(name,
                connection, bean);
        try
        {
            if (!statement.execute())
            {
                return 0;
            }
            final int count = statement.getUpdateCount();
            if (Category.INSERT == category)
            {
                final G2Id id = bean.getClass()
                    .getAnnotation(G2Id.class);
                final String key = id != null ? id.value() : G2Id.DEFAULT;
                serial.getSerialNumber(statement, key, bean);
            }
            return count;
        }
        finally
        {
            statement.close();
        }
    }

    @Override
    public void execute(final Connection connection,
            final Object condition,
            final G2DaoInvoker invoker) throws SQLException,
            PojoPropertiesNotFoundException,
            PojoAccessorValueNotFoundException
    {
        final String name = getSqlName(condition);
        final PreparedStatement preparedStatement = statementFactory.create(
                name, connection, condition);
        if (!preparedStatement.execute())
        {
            preparedStatement.close();
            return;
        }
        final ResultSet resultSet = preparedStatement.getResultSet();
        try
        {
            invoker.execute(resultSet);
        }
        catch (final SQLException e)
        {
            throw e;
        }
        catch (final PojoAccessorValueNotFoundException e)
        {
            throw e;
        }
        catch (final PojoPropertiesNotFoundException e)
        {
            throw e;
        }
        finally
        {
            resultSet.close();
            preparedStatement.close();
        }
    }

    /**
     * @param o
     * @return sql-name の取得
     */
    private String getName(final Object o)
    {
        if (o instanceof Enum<?>)
        {
            return ((Enum<?>) o).name();
        }
        if (o instanceof Class<?>)
        {
            final Class<?> instance = (Class<?>) o;
            return instance.getSimpleName();
        }
        return o.getClass()
            .getSimpleName();
    }

    /**
     * @param condition
     * @return sqlName
     */
    private String getSqlName(final Object o)
    {
        final String type = getName(o);
        if (StringUtils.isEmpty(type))
        {
            throw new SqlNotFoundRuntimeException("type name is empty");
        }
        return "findBy" + type;
    }

    /**
     * @param targetClass
     * @param serial
     * @param sqlMap
     * @param provider
     */
    public G2DaoExecuteInvokerImpl(
        final Class<T> targetClass,
        final G2DaoSerial serial,
        final G2DaoSqlMap sqlMap,
        final InstanceManager provider)
    {
        this.serial = serial;
        this.statementFactory = provider.get(PreparedStatementProvider.class)
            .get(targetClass, sqlMap, provider);
    }

    /**
     * serial
     */
    private final G2DaoSerial serial;

    /**
     * statementFactory
     */
    private final PreparedStatementFactory<T> statementFactory;
}
